<template>
  <div class="profile-page">
    <div class="profile-header">
      <div class="avatar-wrapper">
        <van-image :src="userAvatar" width="80px" height="80px" round />
      </div>
      <div class="user-details">
        <div class="user-name">{{ userInfo.name || '未设置昵称' }}</div>
        <div 
          v-if="!isEditingSignature" 
          class="user-signature" 
          @click="startEditingSignature"
        >
          {{ userInfo.signature || '暂无个性签名' }}
        </div>
        <div v-else>
          <van-field 
            v-model="newSignature" 
            placeholder="请输入新的个性签名" 
            @blur="saveSignature"
            @keyup.enter="saveSignature"
          />
        </div>
        <van-button size="mini" type="primary" @click="goToProfile">完善资料</van-button>
      </div>
    </div>

    <div class="profile-content">
      <!-- 切换标签 -->
      <div class="tab-container">
        <div
          :class="{ 'tab-item': true, active: activeTab === 'works' }"
          @click="activeTab = 'works'"
        >
          作品
        </div>
        <div
          :class="{ 'tab-item': true, active: activeTab === 'liked' }"
          @click="activeTab = 'liked'"
        >
          赞过
        </div>
      </div>
      <!-- 内容区域 -->
      <div class="content-container">
        <div v-if="activeTab === 'works'" class="section">
          <h3>作品</h3>
          <p>这里展示用户的作品</p>
        </div>
        <div v-if="activeTab === 'liked'" class="section">
          <h3>赞过</h3>
          <p>这里展示用户赞过的内容</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import defaultAvatar from '@/assets/images/avatar_default.png';
import { 
  getTokenLocal, 
  getUserLocal, 
} from '@/utils/auth.js';
import { getDetailByIdAPI } from '@/api/user.js';

// 初始化路由
const router = useRouter();

// 状态管理
const userInfo = ref(getUserLocal() || {});
const userAvatar = ref(defaultAvatar);
const activeTab = ref('works');
const isEditingSignature = ref(false);
const newSignature = ref('');

// 从localStorage加载签名
const loadSignature = () => {
  const savedSignature = localStorage.getItem('userSignature');
  if (savedSignature) {
    userInfo.value.signature = savedSignature;
  }
};

// 获取用户详情
const fetchUserDetail = async () => {
  if (!getTokenLocal() || !userInfo.value.id) return;
  
  try {
    const result = await getDetailByIdAPI(userInfo.value.id);
    if (result.data) {
      // 合并本地存储的签名和API获取的用户信息
      userInfo.value = { ...result.data, signature: userInfo.value.signature || result.data.signature };
      userAvatar.value = result.data.avatar ? 'http://www.zjff495.cn:5050/' + result.data.avatar : defaultAvatar;
      // 删除了错误的空赋值语句
    }
  } catch (error) {
    showToast('获取用户信息失败');
    console.error('获取用户信息失败:', error);
  }
};

// 生命周期钩子
onMounted(() => {
  loadSignature(); // 优先加载本地存储的签名
  fetchUserDetail(); // 再从API获取用户信息（如果有）
});

// 跳转到个人资料页面
const goToProfile = () => {
  router.push({ name: 'profile' });
};

// 开始编辑签名
const startEditingSignature = () => {
  isEditingSignature.value = true;
  newSignature.value = userInfo.value.signature || '';
};

// 保存签名到localStorage
const saveSignature = () => {
  if (newSignature.value.trim()) {
    userInfo.value.signature = newSignature.value;
    localStorage.setItem('userSignature', newSignature.value);
    showToast('签名已保存');
  } else {
    showToast('签名不能为空');
  }
  isEditingSignature.value = false;
};

// 监听签名变化，实时更新localStorage
watch(
  () => userInfo.value.signature,
  (newSignature) => {
    if (newSignature) {
      localStorage.setItem('userSignature', newSignature);
    }
  }
);
</script>

<style scoped lang="less">
.profile-page {
  padding: 15px;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;

  .avatar-wrapper {
    margin-right: 20px;
  }

  .user-details {
    .user-name {
      font-size: 18px;
      font-weight: 500;
      margin-bottom: 5px;
    }

    .user-signature {
      font-size: 14px;
      color: #777;
      margin-bottom: 10px;
      cursor: pointer;
      text-decoration: underline;
      text-decoration-color: #ddd;
    }
  }
}

.profile-content {
  .tab-container {
    display: flex;
    margin-bottom: 20px;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 10px;
      cursor: pointer;
      border-bottom: 2px solid #e0e0e0;

      &.active {
        border-bottom-color: #007bff;
        color: #007bff;
      }
    }
  }

  .content-container {
    .section {
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      padding: 20px;
      margin-bottom: 20px;

      h3 {
        font-size: 16px;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
